package com.soo.hoo.admin.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.soo.hoo.admin.model.entity.SysPermission;
import com.soo.hoo.admin.model.vo.TreeVO;
import com.soo.hoo.admin.service.PermissionService;
import com.soo.hoo.core.exception.GlobalException;
import com.soo.hoo.core.model.KeyValue;
import com.soo.hoo.core.model.MatchItem;
import com.soo.hoo.core.model.Page;
import com.soo.hoo.core.model.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>菜单权限管理</p>
 *
 * @author 杨燚
 * @since 2023/4/3
 */
@Tag(name = "权限管理")
@RequestMapping("/permission/")
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PermissionController {

    private final PermissionService permissionService;

    @Operation(summary = "权限树结构")
    @PostMapping("tree")
    public Result<List<Tree<Long>>> tree() {
        return Result.success(permissionService.getPermissionTree());
    }

    @Operation(summary = "权限树结构1", description = "只查询启用的数据")
    @PostMapping("tree1")
    public Result<List<Tree<Long>>> tree(@RequestBody List<MatchItem> matchItems) {
        MatchItem matchItem = new MatchItem();
        matchItem.setColumn("enabled");
        matchItem.setValue(true);
        matchItems.add(matchItem);
        return Result.success(permissionService.tree(matchItems));
    }

    @Operation(summary = "分页", description = "只分页根节点")
    @PostMapping("page")
    public Result<Page<SysPermission>> page(@RequestBody Page<SysPermission> param) {
        return Result.success(permissionService.page(param));
    }

    @Operation(summary = "下属权限列表")
    @GetMapping("listByParentId")
    public Result<List<SysPermission>> listByParentId(@RequestParam Long id) {
        LambdaQueryWrapper<SysPermission> lqw = new LambdaQueryWrapper<SysPermission>()
                .eq(SysPermission::getParentId, id);
        List<SysPermission> list = permissionService.list(lqw);
        return Result.success(list);
    }

    @Operation(summary = "权限列表")
    @GetMapping("list")
    public Result<List<KeyValue>> list() {
        List<KeyValue> retList = new ArrayList<>();
        retList.add(new KeyValue(0L, "根节点"));
        LambdaQueryWrapper<SysPermission> lqw = new LambdaQueryWrapper<SysPermission>()
                .eq(SysPermission::getType, 1);
        List<SysPermission> list = permissionService.list(lqw);
        List<KeyValue> keyValues =
                list.stream().map(e -> KeyValue.builder().key(e.getId()).value(e.getPermissionName()).build()).toList();
        retList.addAll(keyValues);
        return Result.success(retList);
    }

    @Operation(summary = "新增权限")
    @PostMapping("create")
    public Result<Void> create(@RequestBody @Valid TreeVO permission) {
        permissionService.verifyPermission(permission.getParentId(), permission.getName());
        SysPermission p = new SysPermission();
        BeanUtil.copyProperties(permission, p);
        p.setPermissionName(permission.getName());
        p.setHasChildren(false);
        permissionService.save(p);
        SysPermission parent = permissionService.getById(permission.getParentId());
        if (parent != null) {
            parent.setHasChildren(true);
            permissionService.updateById(parent);
        }
        return Result.success();
    }

    @Operation(summary = "更新权限")
    @PostMapping("update")
    public Result<Void> update(@RequestBody @Valid TreeVO permission) {
        if (permission.getId() == null) {
            throw new GlobalException("编辑失败：【编辑时id字段不能为空】");
        }
        SysPermission byId = permissionService.getById(permission.getId());
        // 如果父节点变化，或者权限名称变化，则需要校验是否有重复的权限
        if (!byId.getParentId().equals(permission.getParentId())
                || !byId.getPermissionName().equals(permission.getName())) {
            permissionService.verifyPermission(permission.getParentId(), permission.getName());
        }
        SysPermission p = new SysPermission();
        BeanUtil.copyProperties(permission, p);
        p.setPermissionName(permission.getName());
        p.setHasChildren(byId.getHasChildren());
        permissionService.updateById(p);
        return Result.success();
    }

    @Operation(summary = "删除权限")
    @DeleteMapping("delete")
    public Result<Void> delete(@RequestParam Long id) {
        SysPermission permission = permissionService.getById(id);
        if (permission == null) {
            throw new GlobalException("删除失败，权限不存在");
        }
        permissionService.removeChildren(id);
        LambdaQueryWrapper<SysPermission> lqw = new LambdaQueryWrapper<SysPermission>()
                .eq(SysPermission::getParentId, permission.getParentId());
        List<SysPermission> list = permissionService.list(lqw);
        if (CollUtil.isEmpty(list)) {
            SysPermission parentPermission = permissionService.getById(permission.getParentId());
            parentPermission.setHasChildren(false);
            permissionService.updateById(parentPermission);
        }
        return Result.success();
    }
}
